package com.nio;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class StuNio {

    /**
     * FileChannel 读取
     * @throws IOException
     */
    @Test
    public void ReadFileChannel() throws IOException {
        // 创建FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("F:\\test.txt", "rw");
        FileChannel channel = accessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024); // 创建buffer 分配大小
        //读取数据大小到buffer
        int read = channel.read(buffer);
        while (read != -1){
            System.out.println("读取到了:"+read);
            buffer.flip(); // 读写模式的转换
            // buffer.hasRemaining() 表示里面是否有剩余
            while (buffer.hasRemaining()){
                System.out.println((char) buffer.get());
            }
            buffer.clear();
            read = channel.read(buffer);
        }
        accessFile.close();
        System.out.println("结束了");
    }

    /**
     * FileChannel 写
     */
    @Test
    public void writeFileChannel() throws IOException {
        // 创建channel
        RandomAccessFile accessFile = new RandomAccessFile("F:\\1.txt", "rw");
        FileChannel channel = accessFile.getChannel();
        // 创建buffer对象
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        String data = "qweqweqwewqeq";
        byteBuffer.clear();

        // 写入内容
        byteBuffer.put(data.getBytes());
        byteBuffer.flip();// 读写模式的转换
        while (byteBuffer.hasRemaining()){
            channel.write(byteBuffer);
        }
        // 关闭
        channel.close();
    }


}
